package Test06;

//用对象流读写多个对象（序列化流和反序列化流）

import java.io.*;
import java.util.ArrayList;

/*需求:
将多个自定义对象序列化到文件中，但是由于对象的个数不确定，反序列化流该如何读取呢?
*/
public class Test31 {
    public static void main(String[] args) throws IOException, ClassNotFoundException {

        //1、序列化多个对象
        Student31 s1 = new Student31("zhangsan", 23, "北京");
        Student31 s2 = new Student31("lisi", 24, "上海");
        Student31 s3 = new Student31("王五", 25, "广州");

        ArrayList<Student31> list = new ArrayList<Student31>();
        list.add(s1);
        list.add(s2);
        list.add(s3);

        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("D:\\工作\\src\\b.txt"));

        oos.writeObject(list);

        oos.close();


        //2、反序列化文件

        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("D:\\工作\\src\\b.txt"));

        ArrayList<Student31> newList = (ArrayList<Student31>) ois.readObject();

        for (Student31 student31 : newList) {
            System.out.println(student31);
        }

        ois.close();
    }
}

class Student31 implements Serializable {

    @Serial
    private static final long serialVersionUID = 2623439302548652330L;

    private String name;
    private int age;
    private String address;

    public Student31() {
    }

    public Student31(String name, int age, String address) {
        this.name = name;
        this.age = age;
        this.address = address;
    }

    /**
     * 获取
     *
     * @return name
     */
    public String getName() {
        return name;
    }

    /**
     * 设置
     *
     * @param name
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * 获取
     *
     * @return age
     */
    public int getAge() {
        return age;
    }

    /**
     * 设置
     *
     * @param age
     */
    public void setAge(int age) {
        this.age = age;
    }

    /**
     * 获取
     *
     * @return address
     */
    public String getAddress() {
        return address;
    }

    /**
     * 设置
     *
     * @param address
     */
    public void setAddress(String address) {
        this.address = address;
    }

    public String toString() {
        return "Student31{name = " + name + ", age = " + age + ", address = " + address + "}";
    }
}